package com.gpnu7_412.yanzhi.controller.verification;

import com.gpnu7_412.yanzhi.exception.custom.DataInconsistencyException;
import com.gpnu7_412.yanzhi.service.EmailService;
import com.gpnu7_412.yanzhi.status.Impl.ResultCode;
import com.gpnu7_412.yanzhi.util.Result;
import com.gpnu7_412.yanzhi.util.VerificationCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证控制器
 * @author ZZH
 */
@CrossOrigin
@RestController
@RequestMapping("/verification")
public class VerificationController {

    @Autowired
    private EmailService emailService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取邮箱验证码
     * @param map 请求数据
     * @return 响应数据
     */
    @PostMapping
    public Result sendVerificationCode(@RequestBody Map<String, Object> map) {
        String email = (String) map.get("email");
        if (email == null) {
            throw new DataInconsistencyException("邮箱不能为空");
        }
        // 生成验证码
        String code = VerificationCodeUtil.getRandomCode(6);
        // 发送邮件
        emailService.sendEmail(email, "言智空间", "您正在注册言志空间，验证码：" + code + "有效期五分钟");
        // 将验证码存入 Redis 并设置五分钟过期
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(email, code, 5, TimeUnit.MINUTES);
        return new Result(ResultCode.SUCCESS, "验证码发送成功");
    }
}
